package com.mmlc.meimei.lichengkongjian.mine;

import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.androidnetframe.BaseParentActivity;
import com.androidnetframe.httputil.BaseRequestFilterLayer;
import com.androidnetframe.requestbean.BaseResponseBean;
import com.androidnetframe.responsejavabean.RequestError;
import com.androidnetframe.utils.LogUtils;
import com.mmlc.inter.InterActivity;
import com.mmlc.meimei.lichengkongjian.R;
import com.mmlc.meimei.lichengkongjian.been.ReplaceInfoBean;
import com.mmlc.meimei.lichengkongjian.classify.ProductInfoActivity;
import com.mmlc.meimei.lichengkongjian.customview.ListViewForScrollView;
import com.mmlc.network.filter.GoodsCancelRequestFilter;
import com.mmlc.network.filter.GoodsExchangeRequestFilter;
import com.mmlc.network.filter.SaOderDetailRequestFilter;
import com.mmlc.network.filter.UploadImgRequestFilter;
import com.mmlc.network.responsebean.SellAferOrderDetailResponseBean;
import com.mmlc.utils.ImageTools;
import com.mmlc.utils.PermissionUtils;
import com.mmlc.utils.ToastUtils;
import com.mmlc.utils.UIUtils;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;


/**
 * description: 申请售后
 * by 何强
 * Created at 2016/9/1 15:39
 */
public class ActivityRequestSaleAfter extends InterActivity implements View.OnClickListener,ActivityCompat.OnRequestPermissionsResultCallback {

    @InjectView(R.id.iv_back)
    ImageView ivBack;
    @InjectView(R.id.tv_title)
    TextView tvTitle;
    @InjectView(R.id.tv_suninfo)
    TextView tvSuninfo;
    @InjectView(R.id.rl_title)
    RelativeLayout rlTitle;
    @InjectView(R.id.iv_order)
    ImageView ivOrder;
    @InjectView(R.id.tv_goodsname)
    TextView tvGoodsName;
    @InjectView(R.id.tv_order_specification)
    TextView tvOrderSpecification;
    @InjectView(R.id.tv_order_price)
    TextView tvOrderPrice;
    @InjectView(R.id.tv_order_number)
    TextView tvOrderNumber;
    @InjectView(R.id.tv_serverTypeNone)
    TextView tvServerTypeNone;
    @InjectView(R.id.rb_huan)
    RadioButton rbHuan;
    @InjectView(R.id.rb_tui)
    RadioButton rbTui;
    @InjectView(R.id.rg_group)
    RadioGroup rgGroup;
    @InjectView(R.id.rl_replace)
    RelativeLayout rlReplace;
    @InjectView(R.id.lv_listview)
    ListViewForScrollView lvListview;
    @InjectView(R.id.tv_problemDescNone)
    TextView tvProblemDescNone;
    @InjectView(R.id.lineNone)
    View lineNone;
    @InjectView(R.id.et_input)
    EditText etInput;
    @InjectView(R.id.rl_problemDesc)
    RelativeLayout rlProblemDesc;
    @InjectView(R.id.iva_delete)
    ImageView ivaDelete;
    @InjectView(R.id.iv_a)
    ImageView ivA;
    @InjectView(R.id.rr_a)
    RelativeLayout rrA;
    @InjectView(R.id.ivb_delete)
    ImageView ivbDelete;
    @InjectView(R.id.iv_b)
    ImageView ivB;
    @InjectView(R.id.rr_b)
    RelativeLayout rrB;
    @InjectView(R.id.ivc_delete)
    ImageView ivcDelete;
    @InjectView(R.id.iv_c)
    ImageView ivC;
    @InjectView(R.id.rr_c)
    RelativeLayout rrC;
    @InjectView(R.id.ivd_delete)
    ImageView ivdDelete;
    @InjectView(R.id.iv_d)
    ImageView ivD;
    @InjectView(R.id.rr_d)
    RelativeLayout rrD;
    @InjectView(R.id.iv_post)
    ImageView ivPost;
    @InjectView(R.id.tv_submit)
    TextView tvSubmit;
    @InjectView(R.id.rl_cancelnum)
    RelativeLayout rlCancelNum;
    @InjectView(R.id.tv_requestCount)
    TextView tvRequestCount;
    @InjectView(R.id.tv_cancelInfo)
    TextView tv_cancelInfo;
    @InjectView(R.id.rl_sug)
    RelativeLayout rl_sug;
    public int buycount;

    @Override
    protected int initContentView() {
        return R.layout.activity_request_sale_after;
    }

    @Override
    protected void initView() {
        ButterKnife.inject(this);
        processData();
    }

    String orderId;
    String goodsId;
    String longid;
    String type;

    @OnClick({R.id.iv_sub,R.id.iv_add})
    public void addsub(View view) {
        switch (view.getId()) {
            case R.id.iv_sub:
                sub();
                break;
            case R.id.iv_add:
                add();
                break;
        }
    }

    private void add() {
        String s = tvRequestCount.getText().toString();
        int value = Integer.valueOf(s);
        value = value + 1;
        if(value > Integer.parseInt(goodsnum)){
            value = Integer.parseInt(goodsnum);
        }
        tvRequestCount.setText(value + "");
    }

    private void sub() {
        String s = tvRequestCount.getText().toString();
        int value = Integer.valueOf(s);
        value = value - 1;

        if (value < 1 ) {
            value = 1;
        }
        tvRequestCount.setText(value + "");
    }


    private void processData() {
        UIUtils.updateTextSize(etInput,"在此描述详细问题");
        tvTitle.setText("申请售后");
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        Intent intent = getIntent();
        orderId = intent.getStringExtra("orderId");
        goodsId = intent.getStringExtra("goodsId");
        String tip = intent.getStringExtra("tip");
        if(!TextUtils.isEmpty(tip)){
            tv_cancelInfo.setText(tip);
        }else {
            rl_sug.setVisibility(View.GONE);
        }
        initData();

        rgGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                for (int i = 0; i < group.getChildCount(); i++) {
                    RadioButton rb = (RadioButton) group.getChildAt(i);
                    if (rb.getId() == checkedId) {
                        if (checkedId == R.id.rb_huan) {
                            type = "1";//换货
                            rlReplace.setVisibility(View.VISIBLE);
                            lvListview.setVisibility(View.VISIBLE);
                            rlCancelNum.setVisibility(View.GONE);
                        } else if (checkedId == R.id.rb_tui) {
                            type = "0";//退货
                            rlReplace.setVisibility(View.GONE);
                            lvListview.setVisibility(View.GONE);
                            rlCancelNum.setVisibility(View.VISIBLE);
                        }
                        rb.setTextColor(getResources().getColor(R.color.text_red));
                        rb.setBackgroundResource(R.drawable.shape_border_grey_checked);
                    } else {
                        rb.setTextColor(getResources().getColor(R.color.color_gray_B7B7B7));
                        rb.setBackgroundResource(R.drawable.shape_border_grey);
                    }
                }
            }
        });
        rbHuan.setChecked(true);
    }

    String goodsurl,goodsname,goodsnum,goodsspec="";

    private void initData() {
        initReport();
        SaOderDetailRequestFilter filter = new SaOderDetailRequestFilter((BaseParentActivity) activity);
        filter.requestBean.order_goods_id = Integer.parseInt(goodsId);
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<SellAferOrderDetailResponseBean>() {
            @Override
            public void onSuccess(SellAferOrderDetailResponseBean result) {

                if (result != null) {
                    goodsurl = result.getData().getImg_thumb_min();
                    goodsname = result.getData().getGoods_name();
                    goodsnum = result.getData().getNum();
                    goodsspec = result.getData().getSpec_name();
                    longid = result.getData().getGoods_id() + "";
                    buycount = Integer.parseInt(result.getData().getNum());
                    tvGoodsName.setText(result.getData().getGoods_name() + "");
                    tvOrderSpecification.setText(result.getData().getSpec_name());
                    tvOrderPrice.setText("¥"+result.getData().getPrice() + "");
                    tvOrderNumber.setText("x" + result.getData().getNum());
                    Picasso.with(ActivityRequestSaleAfter.this).load(result.getData().getImg_thumb_min())
                            .into(ivOrder);

                } else {
                    ToastUtils.showToast("无法解析数据");
                }

            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {

            }
        });
        infoList =  new ArrayList<>();
        adapter = new ReplaceListAdapter(infoList,ActivityRequestSaleAfter.this);
        lvListview.setAdapter(adapter);
        lvListview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                buycount = buycount + Integer.parseInt(infoList.get(position).getCount());
                infoList.remove(position);
                adapter.notifyDataSetChanged();
                return false;
            }
        });

    }

    List<ReplaceInfoBean> infoList;

    public  ReplaceListAdapter adapter ;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.inject(this);
    }

    public void tvCancel(View v){
        rl_sug.setVisibility(View.GONE);
    }

    @OnClick({R.id.rl_replace, R.id.iv_post, R.id.tv_submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_replace:
                Intent intent = new Intent(ActivityRequestSaleAfter.this, ProductInfoActivity.class);
                intent.putExtra("type","replace");
                intent.putExtra("long_id",longid);
                intent.putExtra("buy_count",buycount);
                startActivityForResult(intent,100);
                break;
            case R.id.iv_post:
                //6.0动态获取权限
                PermissionUtils.requestPermission(this, PermissionUtils.CODE_READ_EXTERNAL_STORAGE, mPermissionGrant);
                break;
            case R.id.tv_submit:
                doSellAfter();
                break;
        }
    }

    private PermissionUtils.PermissionGrant mPermissionGrant = new PermissionUtils.PermissionGrant() {
        @Override
        public void onPermissionGranted(int requestCode) {
            switch (requestCode) {
                case PermissionUtils.CODE_READ_EXTERNAL_STORAGE:
                    PermissionUtils.requestPermission(ActivityRequestSaleAfter.this, PermissionUtils.CODE_WRITE_EXTERNAL_STORAGE, mPermissionGrant);
                    break;
                case PermissionUtils.CODE_WRITE_EXTERNAL_STORAGE:
                    PermissionUtils.requestPermission(ActivityRequestSaleAfter.this, PermissionUtils.CODE_CAMERA, mPermissionGrant);
                    break;
                case PermissionUtils.CODE_CAMERA:
                    imageSelector(4-picPath_list.size());
                    break;
                default:
                    PermissionUtils.requestPermission(ActivityRequestSaleAfter.this, PermissionUtils.CODE_READ_EXTERNAL_STORAGE, mPermissionGrant);
                    break;
            }
        }
    };
    @Override
    public void onRequestPermissionsResult(final int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        PermissionUtils.requestPermissionsResult(this, requestCode, permissions, grantResults, mPermissionGrant);
    }

    public Handler mHandler;
    public  int time = 0;
    private void doSellAfter() {
        time = 0 ;
        if(rbHuan.isChecked()){
            if(infoList.size()==0){
                ToastUtils.showToast("请选择换货物品");
                return;
            }
            if(TextUtils.isEmpty(etInput.getText().toString().trim())){
                ToastUtils.showToast("请描述详细问题");
                return;
            }
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < infoList.size(); i++) {
                buffer.append(infoList.get(i).getProduct_id()+"-"+infoList.get(i).getCount()+"|");
            }
            String goodsinfo = new String(buffer);
            String desc = etInput.getText().toString();

            postPic(goodsinfo , desc);
//            doRequest(goodsinfo,desc);

        }else if(rbTui.isChecked()){
            if(TextUtils.isEmpty(etInput.getText().toString().trim())){
                ToastUtils.showToast("请描述详细问题");
                return;
            }
            String desc = etInput.getText().toString().trim();
            //handler用于处理图片上传是否完成
            mHandler = new Handler(){
                public int i=0;
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    if(msg.what == 0){
                        i++;
                        if(i == picMap.size()){
                            doCancel(new String(stringBuffer),etInput.getText().toString().trim());

                        }
                    }
                }
            };
            final String str ="";
            if(picMap.size()!=0){
                for (String v : picMap.values()) {
                    //先上传图片
                    commitPhoto(v);
                    //再获取服务器返回的图片地址
                }
            }else {
                doCancel(str,desc);

            }


        }else{
            ToastUtils.showToast("请选择服务类型");
        }
    }

    private void doCancel(String imgs,String desc ) {

        GoodsCancelRequestFilter filter = new GoodsCancelRequestFilter((BaseParentActivity) activity);
        filter.requestBean.order_id = orderId;
        filter.requestBean.order_goods_id = goodsId;
        filter.requestBean.type ="0";
        filter.requestBean.num = tvRequestCount.getText()+"" ;
        filter.requestBean.desc = desc;
        filter.requestBean.imgs = imgs;
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<BaseResponseBean>() {
            @Override
            public void onSuccess(BaseResponseBean result) {
                ToastUtils.showToast("申请退货成功");
                finish();

            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                ToastUtils.showToast(serverError.mess.toString());
            }
        });

    }

    public void postPic(final String goodsinfo , final String desc){

        //handler用于处理图片上传是否完成
        mHandler = new Handler(){
            public int i=0;
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if(msg.what == 0){
                    i++;
                    if(i == picMap.size()){

                        doRequest(goodsinfo,desc,new String(stringBuffer));
                    }
                }
            }
        };
        final String str ="";
        if(picMap.size()!=0){
            for (String v : picMap.values()) {
                //先上传图片
                commitPhoto(v);
                //再获取服务器返回的图片地址
            }
        }else {
            doRequest(goodsinfo,desc,"");
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mHandler!=null){
            mHandler.removeCallbacksAndMessages(null);
        }
        //删除压缩保存在本地的图片
        if(picMap.size()!=0){
            for (String v : picMap.values()) {
                File file = new File(v);
                if(file.exists() && file.isFile()){
                    file.delete();
                }
            }
        }
    }

    public StringBuffer stringBuffer = new StringBuffer();
    private void commitPhoto(final String tmpheader) {
        UploadImgRequestFilter imgFilter = new UploadImgRequestFilter((BaseParentActivity)activity);
        imgFilter.requestParams.addBodyParameter("imgFile", new File(tmpheader));
        imgFilter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e(TAG, "onSuccess: "+result );
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONObject data = jsonObject.getJSONObject("data");
                    stringBuffer.append(data.optString("path")+",");
                    mHandler.sendEmptyMessage(0);
                    time++;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                ToastUtils.showToast(serverError.mess.toString());
            }
        });
    }

    private void doRequest(String goodsinfo,String desc,String imgs) {

        GoodsExchangeRequestFilter filter = new GoodsExchangeRequestFilter((BaseParentActivity) activity);
        filter.requestBean.order_goods_id = Integer.parseInt(goodsId);
        filter.requestBean.goodsinfo = goodsinfo;
        filter.requestBean.desc = desc;
        filter.requestBean.imgs =imgs;
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<BaseResponseBean>() {
            @Override
            public void onSuccess(BaseResponseBean result) {
                ToastUtils.showToast("申请更换成功");
                finish();
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                ToastUtils.showToast(serverError.mess.toString());
            }
        });


    }

    public int count = 0 ;

    //照片缩小的比例
    private static final int SCALE = 2;


    private HashMap<RelativeLayout,String> picPath_list;
    private HashMap<RelativeLayout,String> picMap;
    private ArrayList<ImageView> img_list = new ArrayList<>();
    private ArrayList<RelativeLayout> rr_list = new ArrayList<>();

    private void initReport() {


        img_list.add(ivA);
        img_list.add(ivB);
        img_list.add(ivC);
        img_list.add(ivD);

        rr_list.add(rrA);
        rr_list.add(rrB);
        rr_list.add(rrC);
        rr_list.add(rrD);


        picPath_list = new HashMap<>();
        picMap = new HashMap<>();

    }

    @OnClick({R.id.iva_delete,R.id.ivb_delete,R.id.ivc_delete,R.id.ivd_delete})
    public void delete(View view){
        switch (view.getId()){
            case R.id.iva_delete:
                rrA.setVisibility(View.GONE);
                picPath_list.remove(rrA);
                picMap.remove(rrA);
                img_list.add(ivA);
                rr_list.add(rrA);
                break;
            case R.id.ivb_delete:
                rrB.setVisibility(View.GONE);
                picPath_list.remove(rrB);
                picMap.remove(rrB);
                img_list.add(ivB);
                rr_list.add(rrB);
                break;
            case R.id.ivc_delete:
                rrC.setVisibility(View.GONE);
                picPath_list.remove(rrC);
                picMap.remove(rrC);
                img_list.add(ivC);
                rr_list.add(rrC);
                break;
            case R.id.ivd_delete:
                rrD.setVisibility(View.GONE);
                picPath_list.remove(rrD);
                picMap.remove(rrD);
                img_list.add(ivD);
                rr_list.add(rrD);
                ivPost.setVisibility(View.VISIBLE);
                break;
        }
        if(picPath_list.size()<4){
            ivPost.setVisibility(View.VISIBLE);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //循环接收换货信息


        if(requestCode == 100) {

            if (resultCode == 200 && data!=null){
                List<ReplaceInfoBean> datainfo = new ArrayList<>();
                count = Integer.parseInt(data.getStringExtra("count"));
                String product_id = data.getStringExtra("product_id");
                String spec = data.getStringExtra("spec");
                if(TextUtils.isEmpty(spec)){
                    spec = goodsspec;
                }
                String price = data.getStringExtra("price");
                ReplaceInfoBean replaceInfoBean = new ReplaceInfoBean();
                replaceInfoBean.setCount(count+"");
                replaceInfoBean.setProduct_id(product_id);
                replaceInfoBean.setSpec(spec);
                replaceInfoBean.setPrice(price);
                replaceInfoBean.setName(goodsname);
                replaceInfoBean.setUrl(goodsurl);
                datainfo.add(replaceInfoBean);
                infoList.addAll(datainfo);
                adapter.notifyDataSetChanged();
                if(infoList.size()>0){
                    lvListview.setVisibility(View.VISIBLE);
                }
                buycount = buycount-count;

            }
        }

        //获取相册图片
        if(requestCode == REQUEST_IMAGE&& resultCode ==RESULT_OK && data!=null){
            List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            ContentResolver contentResolver = getContentResolver();
            int currentLen = picPath_list.size();
            for (int i = 0; i < path.size(); i++) {
                LogUtils.e("选择的图片uri", path.get(i));
                Bitmap bitmap = BitmapFactory.decodeFile(path.get(i));
                if (bitmap != null) {
                    Bitmap smallBitmap = ImageTools.zoomBitmap(bitmap, bitmap.getWidth() / SCALE, bitmap.getHeight() / SCALE);
                    bitmap.recycle();
                    img_list.get(i).setImageBitmap(smallBitmap);
                    rr_list.get(i).setVisibility(View.VISIBLE);
                    //将处理过的图片保存到本地
                    String currentHeadPhoto = ImageTools.savePhotoToSDCard(smallBitmap, Environment.getExternalStorageDirectory().getAbsolutePath(), String.valueOf(System.currentTimeMillis()));
                    picPath_list.put(rr_list.get(i),currentHeadPhoto);
                    picMap.put(rr_list.get(i),currentHeadPhoto);
                }
            }
            for (int i = 0; i < path.size(); i++) {
                img_list.remove(0);
                rr_list.remove(0);
            }
            if (picPath_list.size()==4){
                ivPost.setVisibility(View.GONE);
            }
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        adapter.notifyDataSetChanged();
    }


    public static final int REQUEST_IMAGE =700;

    private void imageSelector(int picnums) {
        ArrayList<String> defaultDataArray =  new ArrayList<>();
        Intent intent = new Intent(this, MultiImageSelectorActivity.class);
        // 是否显示调用相机拍照
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        // 最大图片选择数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, picnums);
        // 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/MultiImageSelectorActivity.MODE_MULTI)
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
        // 默认选择图片,回填选项(支持String ArrayList)
        intent.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, defaultDataArray);
        startActivityForResult(intent, REQUEST_IMAGE);
    }

}
